package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.query.StrategyCommentQueryObject;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentMongoRepository repository;

    /**
     * 添加评论的操作
     *
     * @param entity
     */
    public void save(StrategyComment entity) {
        entity.setCreateTime(new Date());
        repository.save(entity);
    }

    /**
     * 查询所有评论的列表
     *
     * @param qo
     * @return
     */
    public Page<StrategyComment> query(StrategyCommentQueryObject qo) {
        //spring Data封装的分页参数(默认从0开始)
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        return repository.findByDetailId(qo.getDetailId(), pageable);
    }

    /**
     * 评论点赞操作
     *
     * @param toId   //当前评论的作者
     * @param fromId //点赞对象的id
     */
    public void commentThumbUp(String toId, Long fromId) {
        //根据id查询评论的对象
        Optional<StrategyComment> op = repository.findById(toId);
        //当对象不为null调用里面的方法
        op.ifPresent(comment -> {
            //取出该评论点赞列表
            List<Long> thumbuplist = comment.getThumbuplist();
            //判断当前点赞列表中是否有点赞对象的id
            if (thumbuplist.contains(fromId)) {
                //包含则取消
                thumbuplist.remove(fromId);
            } else {
                //不包含则取消
                thumbuplist.add(fromId);
            }
            //设置点赞数(即集合的长度)
            comment.setThumbupnum(thumbuplist.size());
            //更新该评论
            repository.save(comment);
        });
    }

}
